<template>
  <q-page class="page" style="background-color: #f5f6fa">
    <!-- <BackHeader title="个人信息" fixed v-if="!useWxHook().isAnyirongMini()" /> -->
    <div @click="showContact" class="flex items-center msg-text">
      <ScrollText bgColor="#fff" :text="msg"></ScrollText>
    </div>
    <img class="bg-img" style="z-index: 1;" src="~/assets/images/infoInput/bg.png" alt="" srcset="">
    <img class="bg-img" style="top: 330px; z-index: 2; opacity: 40%;" src="~/assets/images/infoInput/bg-2.png" alt=""
      srcset="">
    <div class="q-pt-md q-px-md" style="position: relative; z-index: 3;">
      <div class="top-card">
        <img class="top-card-right-bg" src="~/assets/images/infoInput/card-bg-2.png" alt="" srcset="">
        <img class="top-card-middle-bg" src="~/assets/images/infoInput/card-pig.png" alt="" srcset="">
        <div class="top-card-top">
          您已进入极速放款通道
        </div>
        <div class="top-card-bottom">
          <div class="bottom-left">放款速度+80%</div>
          <div class="bottom-right">
            <div class="bottom-right-time">{{ timeString.hours }}</div>
            :
            <div class="bottom-right-time">{{ timeString.minutes }}</div>
            :
            <div class="bottom-right-time">{{ timeString.seconds }}</div>
          </div>
        </div>
      </div>
      <div class="name-info-card bg-white">
        <div class="name-info-card-tips">
          填写真实信息，已有 <span style="color: #FF3C39;">52.8</span> 万人成功下款
        </div>
        <div class="name-info-card-input">
          <div class="flex items-center justify-between no-wrap text-input-box">
            <div class="q-mr-sm" style="color: #666; white-space: nowrap">姓名</div>
            <div class="flex-1" style="width: 100px">
              <input v-model="name" type="text" class="full-width text-right input-nostyle" placeholder="请输入姓名" />
            </div>
          </div>
          <div class="flex items-center justify-between no-wrap text-input-box">
            <div class="q-mr-sm" style="color: #666; white-space: nowrap">身份证号</div>
            <div class="flex-1" style="width: 100px">
              <!-- readonly -->
              <!-- @touchstart.stop="showKeyboard = true" -->
              <input v-model="idCard" type="text" maxlength="18" class="full-width text-right input-nostyle"
                placeholder="请输入身份证号" />
              <!-- <NumberKeyboard
              v-model="idCard"
              :show="showKeyboard"
              extra-key="X"
              close-button-text="完成"
              @blur="showKeyboard = false"
            /> -->
            </div>
          </div>
          <div class="flex items-center justify-between no-wrap text-input-box" @click="areaSelectClickHandler">
            <div class="q-mr-sm" style="color: #666; white-space: nowrap">所在地区</div>
            <div class="flex-1 row justify-end" style="width: 100px">
              <div class="q-mr-xs" :style="!areaName ? { color: '#999' } : {}">{{ areaName || '请选择' }}</div>
              <div class="center">
                <!-- <q-icon name="arrow_forward_ios" style="font-size: 12px; color: #999" /> -->
                <img style="height: 9px;width: 9px; margin-left: 4px;" src="~/assets/images/infoInput/dropdown-icon.png"
                  alt="">
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-if="isOpenOtherInfo" class="name-info-card bg-white" style="margin-top: 9px;">
        <div class="name-info-card-tips">
          补充更多信息，通过率提升<span style="color: #FF3738;">90%</span>
        </div>
        <div class="name-info-card-input">
          <q-list>
            <q-expansion-item v-for="(item, index) in filedList" v-show="currentAllSelectNum >= index" :key="item.id"
              ref="qExpansionItemRefs" group="somegroup">
              <template v-slot:header>
                <q-item-section>
                  <div class="q-mr-sm" style="color: #222222; white-space: nowrap;font-size: 16px;font-weight: 600;">
                    {{ item.name }}
                    <span style="font-weight: 400;font-size: 12px;color: #666666;" v-if="item.filedName == 'orFilter'">资产 <span style="color: #1277FF;">越多</span>，额度 <span
                        style="color: #1277FF;">越高</span></span>
                  </div>
                </q-item-section>
                <q-item-section side>
                  <div v-if="item.filedName != 'orFilter'">
                    {{ filedLabelValues[item.filedName]?.label }}
                  </div>
                </q-item-section>
              </template>
              <div class="bg-white input-section" style="border-radius: 8px; overflow: hidden">
                <section>
                  <!-- @click="filedClickHandler(item)" -->
                  <div class="column justify-between no-wrap">
                    <div class="select-box" style="margin-top: 11px;">
                      <div @click="filedSelectHandler(selectItem)" v-for="(selectItem, index) in item.itemInfoList"
                        :key="selectItem.id" class="select-box-item"
                        :style="checkIsSelect(selectItem.filedName, selectItem.value)">
                        {{ selectItem.name }}
                      </div>
                    </div>
                  </div>
                </section>
              </div>
            </q-expansion-item>
          </q-list>
        </div>
      </div>
      <div class="flex justify-center" style="margin-top: 11px;">
        <img src="~/assets/images/infoInput/protection.png" alt="" style="width: 16px;height: 16px;margin-right: 4px;">
        <span style="font-size: 12px; color: #666666; line-height: 17px;">国家级数据加密保护，仅用于贷款审核</span>
      </div>
    </div>

    <div style="height: 120px"></div>
    <div class="bottom-action-box">
      <q-btn label="下一步" padding="none none" unelevated rounded @click="submit" :loading="loading"
        class="full-width" style="
          background-color: #1277FF;
          color: #fff;
          height: 44px;
          font-size: 15px;
          font-weight: 600;
        " />
      <div class="flex" style="margin-top: 8px;">
        <div :class="{ shake: isShaking }" class="center q-mr-xs" @click="isApprove = !isApprove">
          <img v-if="!isApprove" src="~/assets/images/public/nu_select.png" style="width: 15px" />
          <img v-else src="~/assets/images/public/ok_select.png" style="width: 15px" />
        </div>
        <div style="font-size: 12px; opacity: 0.7; color: #000">
          <span @click="isApprove = true">我已阅读并同意</span><span @click="protocolShow" href="javascript:0;"
            style="color: #1277ff">《个人信息共享授权协议》</span>
        </div>
      </div>
    </div>

    <ActionSheet @select="filedSelectHandler" v-model:show="showActionSheet" :actions="actions" cancel-text="取消"
      close-on-click-action />
    <Popup position="bottom" v-model:show="areaSelectShow">
      <Area :model-value="areaValue || '330102'" @confirm="areaSelectOkHandler" @cancel="areaSelectShow = false"
        title="所在地区" :area-list="areaList" />
    </Popup>
    <BackInfoDialog ref="BackInfoDialogRef" />
    <ContactDialog :isShowUI="false" ref="ContactDialogRef" />
    <CustomAgreementDialog ref="CustomAgreementDialogRef" @confirm="confirmAgreement">
      <ProtocolDialog ref="ProtocolDialogRef" :name="name" :idCard="idCard" :phone="appStore.getSafePhone" />
    </CustomAgreementDialog>
  </q-page>
</template>

<script setup lang="ts">
import { getCommonInfoApi, updateSourceInfoApi } from 'src/api/info';
import BackHeader from 'src/components/BackHeader.vue';
import CustomAgreementDialog from 'src/components/customAgreementDialog/CustomAgreementDialog.vue'
import { CustomAgreementDialogInstance } from 'src/components/customAgreementDialog/CustomAgreementDialog'
import { useAppStore } from 'src/stores/app-store';
import {
  ActionSheetAction,
  ActionSheet,
  Area,
  Popup,
  NumberKeyboard,
  showLoadingToast,
  showToast,
} from 'vant';
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { areaList } from '@vant/area-data';
import { watchEffect } from 'vue';
import { useLocalAMap } from 'src/hooks/local_amap';
import type { MatchResult } from 'src/types/matchResult.d';
import { useMechanismStore } from 'src/stores/mechanism-store'
import ScrollText from 'src/components/ScrollText.vue';
import BackInfoDialog from 'src/components/BackInfoDialog.vue';
import { BackInfoDialogInstance } from 'src/components/BackInfoDialog';
import ProtocolDialog from './components/ProtocolDialog.vue';
import { ProtocolDialogInstance } from './components/ProtocolDialog';
import { getConfigApi } from 'src/api/app'
import ContactDialog from 'src/components/ContactDialog.vue';
import { ContactDialogInstance } from 'src/components/ContactDialog';
import { QExpansionItem } from 'quasar'
import selectItemImage from 'src/assets/images/infoInput/select-item.png';
import selectItemUnImage from 'src/assets/images/infoInput/select-item-un.png';
import { getUserInfoApi } from 'src/api/user';
const appStore = useAppStore();

const route = useRoute();
const showActionSheet = ref(false);
const actions = ref<ActionSheetAction[]>([]);
const isApprove = ref(false);
const ContactDialogRef = ref<ContactDialogInstance>();
const showKeyboard = ref(false);
const msg = ref('')
const BackInfoDialogRef = ref<BackInfoDialogInstance>();
const ProtocolDialogRef = ref<ProtocolDialogInstance>();
const CustomAgreementDialogRef = ref<CustomAgreementDialogInstance>();
const qExpansionItemRefs = ref<QExpansionItem[]>([]);
const indexKeyMap: Record<number, 'province_list' | 'city_list' | 'county_list'> = {
  0: 'province_list',
  1: 'city_list',
  2: 'county_list',
};
const areaValue = ref<string>();
const areaValues = computed(() =>
  areaValue.value && areaValue.value.length === 6
    ? [`${areaValue.value.slice(0, 2)}0000`, `${areaValue.value.slice(0, 4)}00`, areaValue.value]
    : undefined,
);
const areaNames = computed(() => areaValues.value?.map((item, index) => areaList[indexKeyMap[index]][item]));
const areaName = computed(() => areaNames.value?.join('-') ?? '');
const areaSelectShow = ref(false);
const loading = ref(false);
const isShaking = ref(false);
const router = useRouter();
const countdownSeconds = ref(3600);
let intervalId: string | number | NodeJS.Timeout | undefined = undefined;
type FiledResData = {
  filedName: string;
  id: number;
  parentId: number;
  sortWeight: number;
  value: string;
  name: string;
  itemInfoList?: FiledResData[];
};
type LabelValue = {
  label: string;
  value: string;
};
type sysConfig = {
  code: string;
  contentInfo: string;
  name: string;
};
const filedList = ref<FiledResData[]>([]);
const filedLabelValues = ref<Record<string, LabelValue | undefined>>({});
const filedValues = computed(() =>
  Object.fromEntries(Object.entries(filedLabelValues.value).map(([key, value]) => [key, value?.value])),
);
const name = ref('');
const idCard = ref('');
//是否显示其他信息
const isOpenOtherInfo = computed(() => {
  // return true
  return ![name.value, idCard.value, areaName.value].includes("") && idCard.value.length == 18
})
//倒计时
const timeString = computed(() => {
  const hours = Math.floor(countdownSeconds.value / 3600)
    .toString()
    .padStart(2, "0");
  const minutes = Math.floor((countdownSeconds.value % 3600) / 60)
    .toString()
    .padStart(2, "0");
  const seconds = (countdownSeconds.value % 60)
    .toString()
    .padStart(2, "0");

  return {
    hours,
    minutes,
    seconds
  };
});
//当前需要展示的选项数量
const currentAllSelectNum = computed(() => {
  console.log(filedList.value)
  const currentIndex = filedList.value.reduce((curr, item) => {
    if (filedLabelValues.value[item.filedName]?.value) {
      curr++
    }
    return curr
  }, 0)
  nextTick(() => {
    const qeiRef = qExpansionItemRefs.value[currentIndex]
    if (qeiRef) {
      qeiRef.show()
      const el = qeiRef.$el;
      el.scrollIntoView({ behavior: 'smooth' });
    }
  })
  return currentIndex
})
const progress = computed(() => {
  let nameAndIdCardNum = 0;
  if (name.value) nameAndIdCardNum++;
  if (idCard.value) nameAndIdCardNum++;
  if (!filedList.value.length) return nameAndIdCardNum;
  const countNum = filedList.value.length + 3;
  const selectNum = filedList.value.reduce((a, b) => (filedValues.value[b.filedName] ? a + 1 : a), 0);
  return +(((selectNum + (areaValue.value ? 1 : 0) + nameAndIdCardNum) / countNum) * 100).toFixed(0);
});
watch(idCard, () => {
  if (idCard.value.length > 18) {
    idCard.value = idCard.value.slice(0, 18)
  }
})
//同意协议
const confirmAgreement = () => {
  isApprove.value = true;
  submit()
}
//启动倒计时
const startCountdown = () => {
  intervalId = setInterval(() => {
    if (countdownSeconds.value > 0) {
      countdownSeconds.value -= 1;
    } else {
      // 倒计时结束，清除定时器
      clearInterval(intervalId);
    }
  }, 1000);
};
const showContact = () => {
  ContactDialogRef.value?.show()
}
const triggerShake = () => {
  if (isShaking.value) return;

  isShaking.value = true;
  setTimeout(() => {
    isShaking.value = false;
  }, 500);
};
const filedClickHandler = (filed: FiledResData) => {
  actions.value =
    filed.itemInfoList?.map((item) => ({
      name: item.name,
      filedName: filed.filedName,
      value: item.value,
    })) ?? [];
  showActionSheet.value = true;
};
//检查是否选中
const checkIsSelect = (filedName: string, value: string): { color: string, backgroundColor: string } => {
  if (filedLabelValues.value[filedName]?.value.includes(value)) {
    return {
      color: '#FFFFFF',
      backgroundColor: '#1277ff',
      // backgroundImage: `url(${selectItemImage})`
    }
  }
  return {
    color: '#666666',
    backgroundColor: '#f6f6f6',
    // backgroundImage: `url(${selectItemUnImage})`
  }
}
const updateString = (original: string, newValue: string) => {
  let originalArray = original.split(',');
  let index = originalArray.indexOf(newValue);
  if (index !== -1) {
    originalArray.splice(index, 1);
  } else {
    originalArray.push(newValue);
  }
  return originalArray.join(',').replace(/^,|,$/g, '');
}
const filedSelectHandler = (action: ActionSheetAction & { filedName: string; value: string }) => {
  if (!action.name) return;
  //特殊化处理多选
  if (action.filedName == 'orFilter') {
    if(action.value == 'none000' || (action.value != 'none000' && filedLabelValues.value.orFilter?.value == 'none000')){
      filedLabelValues.value.orFilter = { label: action.name, value: action.value }
      console.log(filedLabelValues.value)
      return
    }
    filedLabelValues.value.orFilter = { label: updateString(filedLabelValues.value.orFilter?.label || '', action.name), value: updateString(filedLabelValues.value.orFilter?.value || '', action.value) }
    return 
  }
  filedLabelValues.value[action.filedName] = { label: action.name, value: action.value };
};

const areaSelectClickHandler = () => {
  areaSelectShow.value = true;
};
const areaSelectOkHandler = ({ selectedOptions, selectedValues }: any) => {
  areaValue.value = selectedValues[2];
  areaSelectShow.value = false;
};

const protocolShow = () => {
  CustomAgreementDialogRef.value?.show('')
};

const submit = async () => {
  if (progress.value < 100) {
    if (!name.value) return showToast(`请输入姓名`);
    if (idCard.value.length != 18) return showToast(`请输入合法的身份证号`);
    if (!areaValue.value) return showToast(`请选择地区`);
    const unSelectFiled = filedList.value.find(
      (item) => filedLabelValues.value[item.filedName]?.value === undefined || filedLabelValues.value[item.filedName]?.value === '',
    );
    unSelectFiled ? showToast(`请选择${unSelectFiled.name}`) : '';
    return;
  }
  if (!isApprove.value) {
    protocolShow()
    // showToast('请先同意协议');
    return 
  }
  loading.value = true;
  await useAppStore()
    .updateAuthInfo(idCard.value, name.value)
    .catch((err) => {
      loading.value = false;
      return Promise.reject(err);
    });
  const res = await updateSourceInfoApi<{ matchResult: MatchResult }>({
    ...filedValues.value,
    cityCode: areaValue.value?.slice(0, 4),
  }).finally(() => (loading.value = false));

  const matchResult = res.data.matchResult;

  useMechanismStore().setMatchData(matchResult);

  router.replace({ path: '/waitPage', query: route.query });
};
const getConfigMsg = async () => {
  const res = await getConfigApi<sysConfig>({
    id: 5
  })
  msg.value = res.data.contentInfo
}
const initData = async () => {
  
  getConfigMsg()
  const toast = showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    duration: 0,
  });
  const token = localStorage.getItem("token")
  const resUserInfo = await getUserInfoApi({ token: token }, { diyError: true });
  if(resUserInfo.data.authFlag != 0){
    toast.close();
    router.replace("/waitpage")
  }
  const res = await getCommonInfoApi<{ dataList: FiledResData[] }>().finally(() => {
    toast.close();
  });
  filedList.value = res.data.dataList;
};

initData();

watchEffect(() => {
  const { longitude, latitude } = route.query;
  console.log(longitude, latitude);
  if (longitude && latitude) {
    useLocalAMap()
      .getLocalAddrByPosition(Number(longitude), Number(latitude))
      .then((item) => {
        areaValue.value = item.adcode;
      });
  } else {
    useLocalAMap()
      .getLocalAddress()
      .then((item) => {
        areaValue.value = item.adcode;
      });
  }
});

const popstateHandler = (e: PopStateEvent) => {
  BackInfoDialogRef.value?.show();
  setTimeout(() => {
    window.history.pushState({ infoInputPage: true }, 'infoInputPage', window.location.href);
  });
};

onMounted(() => {
  const { chargeType, isLogin } = useAppStore();
  if ( chargeType != 3) {
    
  }
  startCountdown();
  window.history.pushState({ infoInputPage: true }, 'infoInputPage', window.location.href);
  window.addEventListener('popstate', popstateHandler);
});

onUnmounted(() => {
  if (intervalId) {
    clearInterval(intervalId);
  }
  window.removeEventListener('popstate', popstateHandler);
});
</script>

<style lang="scss" scoped>
/* 抖动动画 */
@keyframes shake {
  0% {
    transform: translate(0, 0);
  }
  10% {
    transform: translate(-5px, -2px);
  }
  20% {
    transform: translate(5px, 2px);
  }
  30% {
    transform: translate(-5px, -2px);
  }
  40% {
    transform: translate(5px, 2px);
  }
  50% {
    transform: translate(-5px, -2px);
  }
  60% {
    transform: translate(5px, 2px);
  }
  70% {
    transform: translate(-5px, -2px);
  }
  80% {
    transform: translate(5px, 2px);
  }
  90% {
    transform: translate(-5px, -2px);
  }
  100% {
    transform: translate(0, 0);
  }
}

/* 动态添加的抖动类 */
.shake {
  animation: shake 0.5s ease;
}
:deep(.q-item) {
  padding: 0;

}

input::-webkit-input-placeholder {
  color: #999;
}

.input-section:not(:first-child) {
  margin-top: 27px;
}

.input-section:last-child {
  margin-bottom: 16px;
}

.select-box {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 9px;

  .select-box-item {
    border-radius: 10px;
    // width: 98px;
    height: 38px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 14px;
    color: #FFFFFF;
    line-height: 20px;
  }
}


.bg-img {
  object-fit: fill;
  width: 100%;
  position: absolute;
  z-index: 0;
}

.name-info-card {
  border-radius: 20px;
  overflow: hidden;

  &-tips {
    padding: 10px 12px;
    background-color: #DEF0FE;
    font-weight: 400;
    font-size: 14px;
    color: #1B2C71;
  }

  &-input {
    padding: 16px 16px 4px 16px;

    .text-input-box {
      background: #F4F6F9;
      border-radius: 12px;
      padding: 16px;
      margin-bottom: 12px;
    }
  }
}

.top-card {
  background-image: url(src/assets/images/infoInput/card-bg.png);
  background-repeat: no-repeat;
  background-size: 100% auto;
  width: 100%;
  height: 82px;
  margin-bottom: 8px;
  padding: 13px;
  display: flex;
  flex-direction: column;
  position: relative;

  &-middle-bg {
    position: absolute;
    top: -10px;
    left: calc(50% - 24px);
    width: 74px;
    height: 91px;
  }

  &-right-bg {
    width: 18.93vw;
    object-fit: cover;
    position: absolute;
    top: 0;
    right: 0;
  }

  &-top {
    font-size: 12px;
    color: #FFFFFF;
  }

  &-bottom {
    display: flex;
    margin-top: 9px;
    justify-content: space-between;
    align-items: center;

    .bottom-left {
      font-weight: 500;
      font-size: 20px;
      color: #FFFFFF;
    }

    .bottom-right {
      display: flex;
      margin-right: 4px;
      font-weight: 400;
      font-size: 14px;
      color: #fff;

      &-time {
        width: 23px;
        height: 26px;
        background: linear-gradient(263deg, #FF7945 0%, #FF3638 100%);
        border-radius: 4px;
        border: 1px solid #FFFFFF;
        margin: 0 4px;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 14px;
      }
    }
  }
}

.msg-text {
  flex-direction: row;
  background-color: #fff;
  padding: 4px 12px;
}

.input-box {
  textarea {
    border: 1px solid #4461e2;
    width: 100%;
    padding: 8px;
    border-radius: 8px;
    font-size: 16px;
  }
}

.bottom-action-box {
  position: fixed;
  z-index: 3;
  padding: 12px 28px;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  border-top: 1px solid rgba($color: #ccc, $alpha: 0.6);
  display: flex;
  flex-direction: column;
  align-items: center;
}
</style>
